package com.julyup.face.controller;

import com.julyup.face.entity.User;
import com.julyup.face.service.UserService;
import com.julyup.face.util.FaceCompareUtils;
import com.julyup.face.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 人脸识别接口
 *
 * @Author: zhenzhong.wang@honeywell.com
 * @Date: 2019/3/22 1:45 PM
 */
@RestController
public class FaceController {

  @Autowired
  UserService userService;

  @PostMapping(value = "/api/face/login")
  public String login(@RequestParam("username") String username , @RequestParam("img") MultipartFile img) throws IOException {
    Double compare = FaceCompareUtils.compare("", "");
    System.out.println("识别相似度：" + compare);
    return "OK";
  }

  @PostMapping(value = "/api/face/register")
  public String register(@RequestParam("username") String username , @RequestParam("img") MultipartFile img) throws IOException {

    String fileName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
        + "-" + UUID.randomUUID()
        + ".jpg";
    FileUtils.writeImageToDisk(img.getBytes(),"/Users/zhenzhong/faceImage/", fileName);

    User oldUser = userService.findByUsername(username);
    if (oldUser != null) {
      oldUser.setFaceImg(fileName);
      userService.save(oldUser);
    } else {
      User user = new User();
      user.setFaceImg(fileName);
      user.setUsername(username);
      userService.save(user);
    }

    return "OK";
  }
}
